<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <!-- :default-expanded-keys="[0]"，展开key值为0的节点，这里是root节点 -->
      <el-form-item label="上级菜单">
        <el-tree-select
          v-model="formData.parentId"
          :data="menuTree"
          :default-expanded-keys="[0]"
          :props="{ ...defaultProps, label: 'name2' }"
          check-strictly
          node-key="id"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="formData.name" clearable placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio v-for="dict in system_menu_type" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单图标" prop="icon" v-if="formData.type !== SystemMenuTypeEnum.Button">
        <IconSelect v-model="formData.icon" clearable />
      </el-form-item>
      <el-form-item label="路由地址" prop="path" v-if="formData.type !== SystemMenuTypeEnum.Button">
        <template #label>
          <Tooltip
            message="访问的路由地址，如：`user`。如需外网地址时，则以 `http(s)://` 开头"
            title="路由地址"
          />
        </template>
        <el-input v-model="formData.path" clearable placeholder="请输入路由地址" />
      </el-form-item>
      <el-form-item
        label="组件地址"
        prop="component"
        v-if="formData.type === SystemMenuTypeEnum.Menu"
      >
        <el-input v-model="formData.component" clearable placeholder="例如：system/user/index" />
      </el-form-item>
      <el-form-item
        label="组件名称"
        prop="componentName"
        v-if="formData.type === SystemMenuTypeEnum.Menu"
      >
        <el-input v-model="formData.componentName" clearable placeholder="例如：SystemUser" />
      </el-form-item>
      <el-form-item
        label="权限标识"
        prop="permission"
        v-if="formData.type !== SystemMenuTypeEnum.Dir"
      >
        <template #label>
          <Tooltip
            message="Controller 方法上的权限字符，如：@PreAuthorize(`@ss.hasPermission('system:user:list')`)"
            title="权限标识"
          />
        </template>
        <el-input v-model="formData.permission" clearable placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="formData.sort" controls-position="right" />
      </el-form-item>
      <el-form-item label="菜单状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in common_enable_status" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="显示状态"
        prop="visible"
        v-if="formData.type !== SystemMenuTypeEnum.Button"
      >
        <template #label>
          <Tooltip message="选择隐藏时，菜单将不会出现在侧边栏，但仍然可以访问" title="显示状态" />
        </template>
        <el-radio-group v-model="formData.visible">
          <el-radio key="true" :value="true">显示</el-radio>
          <el-radio key="false" :value="false">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="总是显示"
        prop="alwaysShow"
        v-if="formData.type !== SystemMenuTypeEnum.Button"
      >
        <template #label>
          <Tooltip
            message="选择不是时，当该菜单只有一个子菜单时，不展示自己，直接展示子菜单"
            title="总是显示"
          />
        </template>
        <el-radio-group v-model="formData.alwaysShow">
          <el-radio key="true" :value="true">总是</el-radio>
          <el-radio key="false" :value="false">不是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="缓存状态"
        prop="keepAlive"
        v-if="formData.type === SystemMenuTypeEnum.Menu"
      >
        <template #label>
          <Tooltip
            message="选择缓存时，则会被 `keep-alive` 缓存，必须填写「组件名称」字段"
            title="缓存状态"
          />
        </template>
        <el-radio-group v-model="formData.keepAlive">
          <el-radio key="true" :value="true">缓存</el-radio>
          <el-radio key="false" :value="false">不缓存</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as MenuApi from '@/api/system/menu'
import type { FormRules } from 'element-plus'
import { EnableStatusEnum, SystemMenuTypeEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import { isExternal } from '@/utils/is'

defineOptions({ name: 'SystemMenuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const { system_menu_type } = useDict(DICT_TYPE.system_menu_type)
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)
const disable_status_label = getDictLabel(DICT_TYPE.common_enable_status, EnableStatusEnum.Disabled)

const dialogVisible = ref(false) // dialog是否展示
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formData = ref({
  id: undefined,
  name: '',
  type: SystemMenuTypeEnum.Dir,
  parentId: 0,
  permission: '',
  path: '',
  icon: '',
  component: '',
  componentName: '',
  visible: true,
  keepAlive: true,
  alwaysShow: true,
  status: EnableStatusEnum.Enabled,
  sort: 0
})
const formRules = reactive<FormRules>({
  parentId: [{ required: true, message: '上级菜单不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单ref

const open = async (type: string, id?: number, parentId?: number, menuType?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (parentId) {
    formData.value.parentId = parentId
  }
  if (menuType) {
    formData.value.type = menuType
  }
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MenuApi.getMenu(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获取部门树
  await getMenuTree()
}

defineExpose({ open })

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  let err = await formValidate(formRef)
  if (err) return
  formLoading.value = true
  try {
    if (
      formData.value.type === SystemMenuTypeEnum.Dir ||
      formData.value.type === SystemMenuTypeEnum.Menu
    ) {
      if (!isExternal(formData.value.path)) {
        if (formData.value.parentId === 0 && formData.value.path.charAt(0) !== '/') {
          message.error('一级菜单路径必须以 / 开头')
          return
        } else if (formData.value.parentId !== 0 && formData.value.path.charAt(0) === '/') {
          message.error('非一级菜单路径不能以 / 开头')
          return
        }
      }
    }
    if (formType.value === 'create') {
      await MenuApi.createMenu(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await MenuApi.updateMenu(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    type: SystemMenuTypeEnum.Dir,
    parentId: 0,
    permission: '',
    path: '',
    icon: '',
    component: '',
    componentName: '',
    visible: true,
    keepAlive: true,
    alwaysShow: true,
    status: EnableStatusEnum.Enabled,
    sort: 0
  }
  formRef.value?.resetFields()
}

const menuTree = ref() // 树形结构
// 获取菜单树
const getMenuTree = async () => {
  menuTree.value = []
  const data = await MenuApi.getMenuSimpleList()
  const menu: Tree & { name2: string } = {
    id: 0,
    name: '主类目',
    name2: '主类目',
    children: []
  }
  data.forEach((item) => {
    item.name2 =
      item.name + (item.status === EnableStatusEnum.Enabled ? '' : ` [${disable_status_label}]`)
  })
  menu.children = handleTree(data)
  menuTree.value.push(menu)
}
</script>

<style scoped lang="scss"></style>
